/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Parser;

import Entities.Content;
import Entities.Header;
import Entities.Mail;
import java.io.*;
import java.util.Properties;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.internet.MimeMessage;

/**
 *
 * @author fabio
 */
public class EmailParser {

    public Mail readMail(Mail mail) throws FileNotFoundException, MessagingException, IOException {

        String filename = mail.getFilename();
        //System.out.println(filename);
        InputStream message;
        message = new FileInputStream(filename);
        Properties props = new Properties();
        Session session = Session.getDefaultInstance(props, null);
        MimeMessage mimeMessage = new MimeMessage(session, message);

        //Parse Header
        HeaderParser parseHeader = new HeaderParser(mail, mimeMessage);
        Header emailHeader = parseHeader.getHeader();
        mail.setHeader(emailHeader);

        //Parse Content
        ContentParser parseContent = new ContentParser(mail, mimeMessage);
        parseContent.run();
        Content emailContent = parseContent.getContent();
        mail.setContent(emailContent);

        return mail;
    }

    public Mail readMail(Mail mail, String mailCorpus) throws FileNotFoundException, MessagingException, IOException {
        //System.out.println(filename);
        InputStream message;
        message = new ByteArrayInputStream(mailCorpus.getBytes());
        Properties props = new Properties();
        Session session = Session.getDefaultInstance(props, null);
        MimeMessage mimeMessage = new MimeMessage(session, message);

        //Parse Header
        HeaderParser parseHeader = new HeaderParser(mail, mimeMessage);
        Header emailHeader = parseHeader.getHeader();
        mail.setHeader(emailHeader);

        //Parse Content
        ContentParser parseContent = new ContentParser(mail, mimeMessage);
        parseContent.run();
        Content emailContent = parseContent.getContent();
        mail.setContent(emailContent);

        System.out.println(mail.toString());

        return mail;
    }
}
